package com.appBase;

import android.app.AlertDialog;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.appBase.tools.FileUtil;
import com.appBase.tools.HttpCallBack;
import com.appBase.tools.HttpData;
import com.appBase.tools.LoadingDialog;
import com.appBase.tools.VersionData;
import com.appBase.tools.YLDownload;
import com.appBase.tools.YLHttpClient;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import static android.widget.Toast.LENGTH_SHORT;

public class JSInterface implements YLDownload.OnDownloadListener {

    private static final int BUFFER_SIZE = 1024;
    private String appBaseUrl = "";
    private MainActivity mContext;
    private String webAppCode = "";
    private String webAppVersion = "";

    private ProgressBar progress;
    private AlertDialog alertDialog1;
    private TextView bai;
    private TextView pici_tb2;
    private TextView pici_tb3;

    private MainActivity mainActivity;

    public boolean webViewCanBack = false;


    public JSInterface(MainActivity context) {
        mContext = context;
    }

    @JavascriptInterface
    public void setWebViewCanBack(String canBack) {
        if (canBack == null) {
            canBack = "false";
        }
        this.webViewCanBack = canBack.equals("true");
    }

    @JavascriptInterface
    public String getAppBaseUrl() {
//        if (this.appBaseUrl.length() > 0) {
//            return this.appBaseUrl;
//        }
//        String path = mContext.getFilesDir().getPath();
//        this.appBaseUrl = FileUtil.getFileContent(path, "url.txt");
////        Toast.makeText(mContext, "wwwwwwwww", Toast.LENGTH_SHORT).show();
////        return this.appBaseUrl;
        return "https://www.twvstock.com";
    }

    @JavascriptInterface
    public void setAppBaseUrl(String url) {
        String path = mContext.getFilesDir().getPath();
        this.appBaseUrl = url;
        FileUtil.setFileContent(path, "url.txt", url);
    }

    @JavascriptInterface
    public void setWebAppCode(String appCode) {
        String path = mContext.getFilesDir().getPath();
        this.webAppCode = appCode;
        FileUtil.setFileContent(path, "webAppCode.txt", appCode);
    }

    @JavascriptInterface
    public String getWebAppCode() {
        if (this.webAppCode.length() > 0) {
            return this.webAppCode;
        }
        String path = mContext.getFilesDir().getPath();
        this.webAppCode = FileUtil.getFileContent(path, "webAppCode.txt");
        if (this.webAppCode == null || "".equals(this.webAppCode)) {
            this.webAppCode = "PDA_WEB";
        }
//        Toast.makeText(mContext, "wwwwwwwww", Toast.LENGTH_SHORT).show();
        return this.webAppCode;
    }

    @JavascriptInterface
    public void setWebAppVersion(String appVersion) {
        String path = mContext.getFilesDir().getPath();
        this.webAppVersion = appVersion;
        FileUtil.setFileContent(path, "webAppVersion.txt", appVersion);
    }

    @JavascriptInterface
    public boolean print(String json) {
        return true;
    }

    @JavascriptInterface
    public String getWebAppVersion() {
        if (this.webAppVersion.length() > 0) {
            return this.webAppVersion;
        }
        String path = mContext.getFilesDir().getPath();
        this.webAppVersion = FileUtil.getFileContent(path, "webAppVersion.txt");
        if (this.webAppVersion == null || "".equals(this.webAppVersion)) {
            this.webAppVersion = "1.0.0";
        }
        return this.webAppVersion;
    }

    @JavascriptInterface
    public void webViewLoaded() {
        LoadingDialog.getInstance(mContext).hide();
    }



    public void updateWebApp() {
        // 特殊情况不需要更新
        if (this.getWebAppVersion().equals("0.0.0")) {
            return;
        }
        JSInterface me = this;
        YLHttpClient.getDefaultYLHttpClient().sendGetRequest(mContext, this.getAppBaseUrl() + "/version/checkVersion?APP_CODE=" + this.getWebAppCode(), new TypeToken<HttpData<VersionData>>() {
        }.getType(), new HttpCallBack<HttpData<VersionData>>() {
            @Override
            public void callBack(int statueCode, HttpData<VersionData> httpData) {
                if (statueCode == 200) {
                    if (!me.getWebAppVersion().equals(httpData.data.APP_VERSION)) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                YLDownload download = new YLDownload();
                                Looper.prepare();
                                String url = httpData.data.FILE_PATH;
                                if (!url.startsWith("http")) {
                                    url = me.getAppBaseUrl() + url;
                                }
                                download.download(url, me.mContext.getFilesDir().getPath(), "web.zip", me);
                                Looper.loop();
                            }
                        }).start();

                        View view1 = View.inflate(me.mContext, R.layout.sync_file, null);
                        progress = (ProgressBar) view1.findViewById(R.id.progressbar_updown1);
                        bai = (TextView) view1.findViewById(R.id.pici_tb4);
                        pici_tb2 = (TextView) view1.findViewById(R.id.pici_tb2);
                        pici_tb3 = (TextView) view1.findViewById(R.id.pici_tb3);
                        progress.setProgress(0);
                        progress.setSecondaryProgress(1);
                        /*bai.setText("0%");*/
                        alertDialog1 = new AlertDialog.Builder(me.mContext)
                                /*.setTitle("这是标题")//标题*/
                                /*.setMessage("这是内容")//内容*/
                                .setView(view1)
                                .create();
                        alertDialog1.show();
                        alertDialog1.setCanceledOnTouchOutside(false);

                    } else {
                        me.startWeb(false);
                    }
                }
            }
        });
    }

    @Override
    public void onDownloadSuccess(File file) {

        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, "更新文件下载成功", LENGTH_SHORT).show();
                alertDialog1.hide();
            }
        });

        unZip(file, this.mContext.getFilesDir().getPath());
        this.startWeb(true);
    }

    @Override
    public void onDownloading(int p) {
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                pici_tb2.setText("更新文件下载中,请耐心等待");
                pici_tb3.setText("下载过程中请保持开机状态");
                progress.setProgress(p);
                progress.setSecondaryProgress(1);
                bai.setText(p + "%");
                Log.i("下载中更新进度条：", String.valueOf(p));
            }
        });
    }

    @Override
    public void onDownloadFailed(Exception e) {
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, "下载异常" + e, LENGTH_SHORT).show();
                if (alertDialog1 != null) {
                    alertDialog1.hide();
                }

            }
        });
    }

    private void startWeb(boolean needReload) {
        if (!needReload) {
            return;
        }
        mContext.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mContext.webView.reload();
//                if (Build.VERSION.SDK_INT > 24) {
//
//                } else {
//                    mContext.webView.reload();
//                    if (lowVersionFirstLoad) {
//                        mContext.webView.reload();
//                    } else {
//                        Toast.makeText(mContext, "当前android版本需要重新启动", LENGTH_SHORT).show();
//                        mContext.serverManager.stopServer();
//                        mContext.finish();
//                    }
//                    lowVersionFirstLoad = false;
//                }

            }
        });
    }

    /**
     * zip解压
     *
     * @param srcFile     zip源文件
     * @param destDirPath 解压后的目标文件夹
     * @throws RuntimeException 解压失败会抛出运行时异常
     */
    public static void unZip(File srcFile, String destDirPath) throws RuntimeException {
        long start = System.currentTimeMillis();

        // 判断源文件是否存在
        if (!srcFile.exists()) {
            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");
        }

        // 开始解压

        ZipFile zipFile = null;

        try {
            zipFile = new ZipFile(srcFile);

            Enumeration<?> entries = zipFile.entries();

            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();

                System.out.println("解压" + entry.getName());

                // 如果是文件夹，就创建个文件夹

                if (entry.isDirectory()) {
                    String dirPath = destDirPath + "/" + entry.getName();
                    File dir = new File(dirPath);
                    dir.mkdirs();

                } else {
                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去
                    File targetFile = new File(destDirPath + "/" + entry.getName());
                    // 保证这个文件的父文件夹必须要存在
                    if (!targetFile.getParentFile().exists()) {
                        targetFile.getParentFile().mkdirs();
                    }
                    targetFile.createNewFile();
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    FileOutputStream fos = new FileOutputStream(targetFile);
                    int len;
                    byte[] buf = new byte[BUFFER_SIZE];
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    fos.close();
                    is.close();
                }

            }

            long end = System.currentTimeMillis();

            System.out.println("解压完成，耗时：" + (end - start) + " ms");

        } catch (Exception e) {
            throw new RuntimeException("unzip error from ZipUtils", e);

        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();

                } catch (IOException e) {
                    e.printStackTrace();

                }

            }

        }

    }

}
